import { useState, useEffect, createContext, useContext } from 'react';
import { useQuery, useMutation, useQueryClient } from 'react-query';
import api from '../services/api';
import toast from 'react-hot-toast';

const AuthContext = createContext();

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const queryClient = useQueryClient();

  // 初始化时检查是否有token
  useEffect(() => {
    const token = localStorage.getItem('accessToken');
    if (!token) {
      setLoading(false);
    }
  }, []);

  // 获取当前用户信息
  const { data: userData, isLoading: userLoading } = useQuery(
    'currentUser',
    () => api.get('/auth/me'),
    {
      enabled: !!localStorage.getItem('accessToken'),
      retry: false,
      onError: () => {
        localStorage.removeItem('accessToken');
        localStorage.removeItem('refreshToken');
        setUser(null);
        setLoading(false);
      },
    }
  );

  // 登录
  const loginMutation = useMutation(
    (credentials) => api.post('/auth/login', credentials),
    {
      onSuccess: (response) => {
        const { user, tokens } = response.data;
        localStorage.setItem('accessToken', tokens.access_token);
        localStorage.setItem('refreshToken', tokens.refresh_token);
        setUser(user);
        toast.success('登录成功！');
        queryClient.invalidateQueries('currentUser');
      },
      onError: (error) => {
        toast.error(error.response?.data?.error || '登录失败');
      },
    }
  );

  // 注册
  const registerMutation = useMutation(
    (userData) => api.post('/auth/register', userData),
    {
      onSuccess: (response) => {
        const { user, tokens } = response.data;
        localStorage.setItem('accessToken', tokens.access_token);
        localStorage.setItem('refreshToken', tokens.refresh_token);
        setUser(user);
        toast.success('注册成功！');
        queryClient.invalidateQueries('currentUser');
      },
      onError: (error) => {
        toast.error(error.response?.data?.error || '注册失败');
      },
    }
  );

  // 登出
  const logoutMutation = useMutation(
    () => api.post('/auth/logout'),
    {
      onSuccess: () => {
        localStorage.removeItem('accessToken');
        localStorage.removeItem('refreshToken');
        setUser(null);
        queryClient.clear();
        toast.success('已退出登录');
      },
      onError: () => {
        // 即使API调用失败，也要清除本地状态
        localStorage.removeItem('accessToken');
        localStorage.removeItem('refreshToken');
        setUser(null);
        queryClient.clear();
      },
    }
  );

  // 修改密码
  const changePasswordMutation = useMutation(
    (passwordData) => api.post('/auth/change-password', passwordData),
    {
      onSuccess: () => {
        toast.success('密码修改成功！');
      },
      onError: (error) => {
        toast.error(error.response?.data?.error || '密码修改失败');
      },
    }
  );

  // 刷新令牌
  const refreshToken = async () => {
    try {
      const refreshTokenValue = localStorage.getItem('refreshToken');
      if (!refreshTokenValue) {
        throw new Error('No refresh token');
      }

      const response = await api.post('/auth/refresh', {}, {
        headers: {
          Authorization: `Bearer ${refreshTokenValue}`,
        },
      });

      const { access_token } = response.data;
      localStorage.setItem('accessToken', access_token);
      return access_token;
    } catch (error) {
      localStorage.removeItem('accessToken');
      localStorage.removeItem('refreshToken');
      setUser(null);
      throw error;
    }
  };

  // 更新用户状态
  useEffect(() => {
    if (userData) {
      setUser(userData.data.user);
      setLoading(false);
    } else if (!userLoading) {
      setLoading(false);
    }
  }, [userData, userLoading]);

  const value = {
    user,
    loading,
    login: loginMutation.mutate,
    register: registerMutation.mutate,
    logout: logoutMutation.mutate,
    changePassword: changePasswordMutation.mutate,
    isLoggingIn: loginMutation.isLoading,
    isRegistering: registerMutation.isLoading,
    isLoggingOut: logoutMutation.isLoading,
    isChangingPassword: changePasswordMutation.isLoading,
  };

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};
